
<template>
  <!-- 离职申请 -->
  <div>
    <el-row :gutter="24">
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="primary" plain @click="add" style="width: 100px;">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导入
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain style="border: none;">
          导出
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>
      
      <el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="danger" plain @click="handleDelete">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </div>
      </el-col><el-col :span="2">
        <div class="grid-content ep-bg-purple">
          <el-button type="success" plain @click="handleAudit" :disabled="selectedRows.length === 0">
            <el-icon><Check /></el-icon>审核
          </el-button>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      
      <el-col :span="4">
        <div class="grid-content ep-bg-purple-light">
          <el-input 
            v-model="keyword" 
            style="width: 180px" 
            size="large"
            placeholder="搜索"
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-col>

      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="dialog = true">
              <el-icon><Filter /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="1">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="排序" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default">
              <el-icon><Sort /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>

      <el-col :span="2">
        <div class="grid-content ep-bg-purple-light">
          <a-tooltip content="刷新" position="bottom" background-color="rgb(52, 145, 250)" mini>
            <el-button size="default" @click="fetchData">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </a-tooltip>
        </div>
      </el-col>
    </el-row>

    <el-table 
      :data="data" 
      border 
      style="width: 100%;" 
      @cell-dblclick="handleClick"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed="left" label="选择" width="50" />
      <el-table-column prop="employeeName" label="员工姓名" width="120" />
      <el-table-column prop="employeeId" label="工号" width="120" />
      <el-table-column prop="idCardNumber" label="身份证号" width="180" />
      <el-table-column prop="department" label="部门" width="120" />
      <el-table-column prop="position" label="岗位" width="120" />
      <el-table-column prop="employmentForm" label="聘用形式" width="120" />
      <el-table-column prop="entryDate" label="入职时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.entryDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="departmentHead" label="部门主管" width="120" />
      <el-table-column prop="handlingHr" label="经办HR" width="120" />
      <el-table-column prop="expectedResignationDate" label="预计离职时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.expectedResignationDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="reasonForResignation" label="离职原因" width="120" />
      <el-table-column prop="workHandoverPerson" label="工作交接人" width="120" />
      <el-table-column prop="workHandoverConfirmation" label="工作交接确认" width="150" />
      <el-table-column prop="financialHandoverConfirmation" label="财务交接确认" width="150" />
      <el-table-column prop="administrativeHandoverConfirmation" label="行政交接确认" width="150" />
      <el-table-column prop="personnelHandoverConfirmation" label="人事交接确认" width="150" />
      <el-table-column prop="officialResignationDate" label="正式离职日期" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.officialResignationDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="hrConfirmation" label="HR确认" width="120" />
      <el-table-column prop="applicationDate" label="提交时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.applicationDate) }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination 
      v-model:current-page="currentPage" 
      v-model:page-size="pageSize" 
      :page-sizes="[10, 20, 30, 40]"
      :disabled="disabled" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total"
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog v-model="auditDialogVisible" title="确认审核" width="30%" center>
    <div style="text-align: center; padding: 20px 0;">
      <el-icon style="font-size: 40px; color: #409EFF; margin-bottom: 10px;">
        <Warning />
      </el-icon>
      <p>确定要审核通过选中的 {{ selectedRows.length }} 条离职记录吗？</p>
      <p style="color: #999; font-size: 12px;">审核通过后将更新HR确认状态</p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAudit" :loading="auditLoading">确认审核</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 详情页面 -->
    <el-dialog title="详细信息" v-model="isVisible" fullscreen destroy-on-close @close="handleDialogClose">
      <hr />
      <DetailsOfTheTalent 
        :resignation-data="selectedResignationData"
        @update-success="handleUpdateSuccess"
        @cancel="isVisible = false">
      </DetailsOfTheTalent>
    </el-dialog>
    
    <!-- 添加页面 -->
    <el-dialog title="添加离职申请" v-model="AddDisplay" fullscreen destroy-on-close @close="handleAddDialogClose">
      <OnboardingAddition @added="onResignationAdded" @close="handleAddDialogClose"></OnboardingAddition>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%" center>
      <div style="text-align: center; padding: 20px 0;">
        <el-icon style="font-size: 40px; color: #F56C6C; margin-bottom: 10px;">
          <Warning />
        </el-icon>
        <p>确定要删除选中的 {{ selectedRows.length }} 条离职记录吗？</p>
        <p style="color: #999; font-size: 12px;">此操作不可恢复，请谨慎操作</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!--筛选-->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="form" style="height: 600px;">
          <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
            <template #label="{ label, value }">
              <span style="font-weight: bold">{{ label }}</span>
            </template>
            <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import OnboardingAddition from '@/views/onboarding/dimission/insert.vue'
import DetailsOfTheTalent from '@/views/onboarding/dimission/detailed.vue'
import axios from 'axios'

const isVisible = ref(false)
const AddDisplay = ref(false)
const loading = ref(false)
const dialog = ref(false)
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const disabled = ref(false)
const total = ref(0)
const data = ref([])
const selectedResignationData = ref({})
const keyword = ref('')
const selectedRows = ref([])

// 获取数据
const fetchData = async () => {
  try {
    const response = await axios.get('/api/resignation/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        keyword: keyword.value,
        filter: Screening.value
      }
    })
    
    if (response.data.code === 200) {
      data.value = response.data.data
      total.value = response.data.total
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取数据失败: ' + (error.response?.data?.message || error.message))
    console.error(error)
  }
}
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const handleAudit = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要审核的记录')
    return
  }
  auditDialogVisible.value = true
}
const confirmAudit = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('没有选中的记录')
    return
  }
  
  auditLoading.value = true
  
  try {
    selectedRows.value.forEach(row => {
      const index = data.value.findIndex(item => item.resignationId === row.resignationId)
      if (index !== -1) {
        data.value[index].hrConfirmation = '已确认'
      }
    })
    
    ElMessage.success('审核成功')
    auditDialogVisible.value = false
    // 清空选择
    selectedRows.value = []
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  } finally {
    auditLoading.value = false
  }
}
// 处理更新成功事件
const handleUpdateSuccess = (updatedData) => {
  // 更新列表中的数据
  const index = data.value.findIndex(item => item.resignationId === updatedData.resignationId)
  if (index !== -1) {
    data.value[index] = { ...updatedData }
  }
  // 关闭详情对话框
  isVisible.value = false
  // 显示成功消息
  ElMessage.success('更新成功')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const form = ref()
const Screening = ref('')
const FilterData = ref([
  { value: '', label: '全部' },
  { value: 'HR已确认', label: 'HR已确认' },
  { value: 'HR未确认', label: 'HR未确认' }
])

const onClick = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    dialog.value = false
    fetchData()
  }, 400)
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

// 处理表格双击事件，显示详细信息
const handleClick = (row) => {
  selectedResignationData.value = { ...row } 
  isVisible.value = true
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 点击删除按钮
const handleDelete = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning('没有选中的记录')
    return
  }
  
  deleteLoading.value = true
  
  try {
    // 获取选中记录的ID列表
    const ids = selectedRows.value.map(row => row.resignationId)
    
    // 调用删除接口
    const response = await axios.delete('/api/resignation/delete', {
      data: { ids: ids }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      // 重新加载数据
      fetchData()
    } else {
      ElMessage.error('删除失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteLoading.value = false
  }
}

// 打开添加对话框
const add = () => {
  AddDisplay.value = true
}

// 离职申请添加成功后的回调
const onResignationAdded = () => {
  AddDisplay.value = false
  fetchData()
}

// 处理添加对话框关闭
const handleAddDialogClose = () => {
  AddDisplay.value = false
}

// 处理对话框关闭
const handleDialogClose = () => {
  isVisible.value = false
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped></style>